#!/usr/bin/python
#
# Copyright (c) 2020 NVI, Inc.
#
# This file is part of VLBI Field System
# (see http://github.com/nvi-inc/fs).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

import socket
#import netstring
import os
import sys
import getopt
import string
import select
from subprocess import call
    
parms = {'-h': '127.0.0.1', '-p':5000, '-t':1,'-c': "dbe_atten?;",
         '-n': os.path.basename(__file__)}
try:
    opts, pargs = getopt.getopt(sys.argv[1:], "h:p:c:t:n:")
except getopt.GetoptError, msg:
    sys.exit(msg)

for o,v in opts:
    #print o,v
    parms[o] = v

host = str(parms['-h'])
port = int(parms['-p'])
mycmd = str(parms['-c'])
timeout=float(parms['-t'])
name= str(parms['-n'])
#print "Host:", host, "port:", port, "cmd:", mycmd," Timeout: ",timeout

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
     s.connect ((host,port))
except socket.timeout:
    call(["lgerr","lg","-1",
         name+': '+host+': '+"Connection time-out"])
#    print "Connection time-out"
    sys.exit()
except socket.error, e:
    call(["lgerr","lg","-1",
          name+': '+host+': '+"error %s"%(e)])
#          name+': '+host+': '+"error {0}: {1}".format(e.errno, e.strerror)])
#    print host+': '+"error {0}:{1}".format(e.errno, e.strerror)
    sys.exit()

# ADD \n TO END IF NOT THERE
mycmd = string.strip(mycmd)
mycmd = mycmd + '\n'
        
# SEND COMMAND
#print mycmd
rv = s.send(mycmd)
if rv <= 0 :
    print "Fail to send ", rv
            
# WAIT FOR RESPONSE
ready=select.select([s], [], [],timeout)
if ready[0]:
    ret = s.recv(8192)
    ret=string.rstrip(ret,"\n")
    print ret
else:
    call(["lgerr","lg","-1",
          name+': '+host+': '+"Read time-out"])
#    print "Read time-out"

s.close()

